﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyWebApp.Common.SlideCaptcha;
using MyWebApp.Helper;
using System;
using System.Collections;

namespace MyWebApp.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class SlideCaptController : Controller
    {
        [HttpGet]
        public IActionResult GetCaptcha()
        {
            Captcha64Model model = Captcha.GenerateBase64();
            CacheHelper.SetCache("sliderX", model.X);
            Hashtable ht = new Hashtable();
            ht.Add("background", model.Background);
            ht.Add("slider", model.Slide);
            ht.Add("sliderX", model.X);
            return Json(ht);
        }

        /// <summary>
        /// 检查验证
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CheckCaptcha([FromQuery] int x = 0)
        {
            Hashtable hs = new Hashtable();
            string Mess = "";
            int Code = 0;
            var session = CacheHelper.GetCache("sliderX");
            if (session == null)
            {
                Mess = "请刷新验证码";
                Code = 500;
                goto block;
            }
            string sliderXStr = session?.ToString();// as string
            int sliderX = Convert.ToInt32(sliderXStr);
            int difX = sliderX - x;
            if (difX >= 0 - Config.blod && difX <= Config.blod)
            {
                Mess = "success";
                Code = 0;
            }
            else
            {
                session = null;
                Mess = "fail";
                Code = 500;
            }
            block:
            hs.Add("Mess", Mess);
            hs.Add("Code", Code);
            return Json(hs);
        }
    }
}
